package com.aat.dxfy.base.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;

@WebFilter("/*")
public class CommonFilter implements Filter {

	public CommonFilter() {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse rep, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) rep;
		// 路径信息加入SESSION
		request.getSession().setAttribute("path", request.getContextPath());

		// JSESSIOND
		if (request.isRequestedSessionIdFromURL()) {
			HttpSession session = request.getSession();
			if (session != null) {
				session.invalidate();
			}
		}
		//
		HttpServletResponseWrapper wrappedResponse = new HttpServletResponseWrapper(response) {
			public String encodeRedirectUrl(String url) {
				return url;
			}

			public String encodeRedirectURL(String url) {
				return url;
			}

			public String encodeUrl(String url) {
				return url;
			}

			public String encodeURL(String url) {
				return url;
			}
		};

		// XSS
		chain.doFilter(new XssHttpServletRequestWrapper(request), wrappedResponse);

	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
